<template>
  <div class="app-container">
	<el-table
	  v-loading="loading"
	  :data="manualHygieneList"
	  row-key="id"
	  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">


		<el-table-column prop="name" label="名称" :show-overflow-tooltip="true" />


		<el-table-column label="操作" align="center" >
		  <template slot-scope="scope">
			  <el-button
			          v-if="scope.row.type== 2"
			          size="mini"
			          circle type="success"
			          icon="el-icon-edit"
			          @click="dormHygiene(scope.row)"
			          v-hasPermi="['basedata:bshygiene:add']"/>

			  <el-button
					  v-if="scope.row.type== 2"
			          size="mini"
			          circle
			          icon="el-icon-circle-check"
			          @click="studentHygiene(scope.row)"
			          v-hasPermi="['system:role:edit']"
			  />
		  </template>
		</el-table-column>
	</el-table>
	<!-- 宿舍卫生考核 -->
	<el-dialog :title="dormTitle" :visible.sync="dormOpen" width="600px"  >
		<el-form ref="form" :model="form" :rules="rules" label-width="120px">
			<el-row :gutter="10" class="mb8" >
			  <el-col :span="1.5">
			    <el-form-item label="卫生检查日期：">
			    <el-date-picker
			      v-model="form.checkDate"
			      size="small"
			      style="width: 140px"
			      value-format="yyyy-MM-dd" @change="changeHygieneDate"/>
			    </el-form-item>
			  </el-col>
			</el-row>

			<el-row :gutter="10" class="mb8" >
			  <el-col :span="1.5">
			    <el-form-item label="等级 : " prop="grade">
				   <input type="radio" v-model="form.grade" value="1" name="grade" />优秀 &nbsp;&nbsp;
				   <input type="radio" v-model="form.grade" value="2" name="grade"/>良好  &nbsp;&nbsp;
				   <input type="radio" v-model="form.grade" value="3" name="grade"/>差  &nbsp;&nbsp;
			    </el-form-item>
			  </el-col>
			</el-row>
			<el-row :gutter="10" class="mb8" >
			  <el-col :span="1.5">
			    <el-form-item label="备注:" prop="remark">
			        <el-input v-model="form.remark"  />
			    </el-form-item>
			  </el-col>
			</el-row>

			<el-row>
			    <el-col :span="1.5">
					<el-form-item label="照片">
						<el-upload
							ref="upload"
							:action="activeUrl"
							:data="form"
							:auto-upload="false"
							multiple="multiple"
							:on-change="uploadChange"
							name="upload"
							list-type="picture"
							:limit="1"
							:file-list="fileList"
							:on-exceed="onExceed"
							:headers="headers"
							:before-upload="beforeUpload"
							:on-preview="handlePreview"
							:on-success="handleSuccess"
							:on-remove="handleRemove">
							<i class="el-icon-plus"></i>
						</el-upload>
						<el-input v-model="form.photo" type="hidden" />
					 </el-form-item>
			    </el-col>
			</el-row>
			<el-row>
			    <el-col :span="1.5" v-if="dialogVisible">
			            &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
			    </el-col>
			    <el-col :span="1.5" v-if="dialogVisible">
			            <img width="100" height="100" :src="dialogImageUrl" alt="">
			    </el-col>
			</el-row>
		</el-form>
		<div slot="footer" class="dialog-footer">
		    <el-button type="primary" @click="submitForm">确 定</el-button>
		    <el-button @click="cancel">取 消</el-button>
		</div>
	</el-dialog>

	<!-- 个人卫生考核 -->

	<el-dialog :title="studentTitle" :visible.sync="studentHygieneOpen" width="600px"  >
	  <el-form ref="studentForm" :model="studentForm" :rules="rules" label-width="100px">

		  <el-form-item label="考勤时间：">
			<el-date-picker
			  v-model="studentForm.checkDate"
			  size="small"
			  style="width: 140px"
			  value-format="yyyy-MM-dd" @change="changeCheckDate" />
		  </el-form-item>

		  <el-table :data="studentHygieneList">
			  <el-table-column prop="studentName" label="学生名称" :show-overflow-tooltip="true" />
			  <!--
			  <el-table-column prop="grade" label="卫生评级" :show-overflow-tooltip="true" />
			  -->

			  <el-table-column label="操作" align="center" >
				 <template slot-scope="scope">

					<label v-for="item in gradeList" :key="item.value" >

						<span v-if="scope.row.grade===item.value">

							<input type="radio"  checked="checked" :name="scope.row.studentNo"  :value="item.value" @click="changegGrade">{{item.label}}
						</span>
						<span v-else>
							<input type="radio"  :name="scope.row.studentNo"  :value="item.value" @click="changegGrade">{{item.label}}
						</span>
					</label>
			    </template>
			  </el-table-column>

		  </el-table>
	   </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button type="primary" @click="submitStudentForm">确 定</el-button>
	    <el-button @click="cancel">取 消</el-button>
	  </div>
	</el-dialog>


  </div>
</template>

<script>
	import { getToken } from '@/utils/auth'
import { getManualHygieneList,getHygieneByDormitoryIdAdndCheckDate,addHygiene,updateHygiene } from "@/api/smartdor/sdmanualHygiene.js"
 import { getStuByCheckDateAndBdormitoryId,addStudentHygiene} from "@/api/smartdor/sdStudentHygiene.js"
export default {
  name: "Menu",
  computed:{
      headers(){
        return {
          Authorization: "Bearer " + getToken()
        }
      }
  },
  data() {
    return {
		//上传的路径
		activeUrl: '',
	    dormOpen: false,
		//判断是否上传文件
		isHaveFile: false,
	    // 弹出宿舍卫生层标题
	    dormTitle: "",
		// 非多个禁用
		multiple: true,
		photo:'',
	    isChange:false,
	    remark:undefined,
	    fileList: [],
        // 遮罩层
        loading: true,
	    // 卫生列表
	    manualHygieneList:[],
        // 是否显示宿舍考核弹出层
        open: false,

		buildingNo:undefined,
		//楼层
		storey:undefined,
		//宿舍ID
		bdormitoryId:undefined,
		//宿舍号
		dormitoryNo:undefined,

		//----- 学生卫生考核操作块 ---------------
		// 是否显示学生考核弹出层
		studentTitle:undefined,
		studentHygieneOpen: false,
		studentNoArray:[],
		gradeArray:[],
		gradeList:[{label:"优秀",value:'1'},{label:"良好",value:'2'},{label :"差" , value:'3'}],
		studentHygieneList:[],
		// 学生卫生考核查询参数
		studentHygieneQueryParams: {
			checkDate: undefined,
			bdormitoryId: undefined
		},
		// 学生卫生考核表单
		studentForm:{
			checkDate : new Date(),
			//第几栋楼
			buildingNo:undefined,
			//楼层
			storey:undefined,
			//宿舍ID
			bdormitoryId:undefined,
			//宿舍号
			dormitoryNo:undefined,
			// 评级
			grade:undefined,
			studentNoArray:[],
			gradeArray:[]
		}

		,
		// 查询参数
		queryParams: {
			checkDate: undefined,
			dormitoryId: undefined,
		},
		// 表单参数
		form: {
			id: undefined,
			checkDate:new Date(),
			//第几栋楼
			buildingNo:undefined,
			//楼层
			storey:undefined,
			//宿舍ID
			bdormitoryId:undefined,
			//宿舍号
			dormitoryNo:undefined,
			remark:undefined,
			grade:undefined
		},
		dialogVisible: false,
		dialogImageUrl: '',
		// 表单校验
		rules: {
			attenceDate: [
				{ required: true, message: "考勤时间不能为空", trigger: "blur" }
			]
		}
    };
  },

  created() {
    this.getList();
  },
  methods: {
	//文件状态改变
	uploadChange: function (file, fileList) {
	    if (fileList.length > 0) {
	        this.isHaveFile = true;
	    } else {
	        this.isHaveFile = false;
	    }
	},
	//文件上传成功的钩子函数
	handleSuccess(res, file) {
		//alert("文件上传成功..........."+this.form.id +"\t this.form.id !== undefined : "+(this.form.id !== undefined))
	    if (this.form.id !== undefined) {
			this.$message({
			  type: 'info',
			  message: '操作成功',
			  duration: 6000
			});
			//关闭弹出层
			this.dormOpen = false;
			this.$refs.upload.clearFiles();
			this.reset() ;
	    }
	},
	//删除文件之前的钩子函数
	handleRemove(file, fileList) {
	    this.$message({
	    	type: 'info',
	    	message: '已删除原有图片',
	    	duration: 6000
	    });
		this.isHaveFile = false;
	},
	//点击列表中已上传的文件事的钩子函数
	handlePreview(file) {
	},
	//上传的文件个数超出设定时触发的函数
	onExceed(files, fileList) {
	    this.$message({
	    type: 'info',
	    message: '最多只能上传一个图片',
	    duration: 6000
	    });
	},
	//文件上传前的前的钩子函数
	//参数是上传的文件，若返回false，或返回Primary且被reject，则停止上传
	beforeUpload(file) {
	    const isJPG = file.type === 'image/jpeg';
	    const isGIF = file.type === 'image/gif';
	    const isPNG = file.type === 'image/png';
	    const isBMP = file.type === 'image/bmp';
	    const isLt2M = file.size / 1024 / 1024 < 2;

	    if (!isJPG && !isGIF && !isPNG && !isBMP) {
	        this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!');
	    }
	    if (!isLt2M) {
	        this.$message.error('上传图片大小不能超过 2MB!');
	    }
	},
    /** 查询列表 */
    getList() {
      this.loading = true;
	  getManualHygieneList(this.queryParams).then(response => {
			  this.manualHygieneList = this.handleTree(response.data, "id");
			  this.loading = false;
	  });
    },

	format_date(){
		let month = this.studentForm.checkDate.getMonth()+1;
		if(month<10){
			month = "0"+month;
		}
		let date = this.studentForm.checkDate.getDate();
		if(date <10){
			date = "0"+date;
		}
		let access_date= this.studentForm.checkDate.getFullYear()+"-"+month+"-"+date;
		return access_date ;
	}
	,
	// 寝室对应的学生操作
	studentHygiene(row){

		//this.studentHygieneOpen = true;

		this.studentForm.buildingNo = row.building_no;
		this.studentForm.storey = row.storey;
		this.studentForm.bdormitoryId = row.id;
		this.studentForm.dormitoryNo = row.name;
		this.studentForm.checkDate =  new Date();
		let _checkDate= this.format_date();
		this.studentHygieneQueryParams.checkDate =_checkDate;
		this.studentHygieneQueryParams.bdormitoryId = row.id;
		getStuByCheckDateAndBdormitoryId(this.studentHygieneQueryParams).then(response=> {
			this.studentHygieneOpen = true;
			this.studentTitle = "学生卫生考核列表";
			this.studentHygieneList = response.data ;
			this.initStudentNoArrayAndGradeArray();
		})

	},
	initStudentNoArrayAndGradeArray(){

		this.studentNoArray=[];
		this.gradeArray = [];
		for(var i=0;i<this.studentHygieneList.length;i++){
			if(this.studentHygieneList[i].grade>0){
				this.studentNoArray.push(this.studentHygieneList[i].studentNo);
				this.gradeArray.push(this.studentHygieneList[i].grade);
			}
		}

		this.studentForm.studentNoArray = this.studentNoArray;
		this.studentForm.gradeArray = this.gradeArray;

		//alert(this.studentForm.studentNoArray +"       "+this.studentForm.gradeArray);

	},
	changegGrade(e){
		let current_that = e.currentTarget

		// alert(current_that.name +"      "+current_that.value);
		for(var i=0;i<this.studentNoArray.length;i++){
			//alert("已经保存到数组中的元素：" +this.studentNoArray[i]+"----------"+this.statusArray[i]);
		    if(this.studentNoArray[i] ==current_that.name ){
		    	this.studentNoArray.splice(i,1);  // 删除数组元素
				this.gradeArray.splice(i,1);  // 删除数组元素
		    }
		}

		this.studentNoArray.push(current_that.name);
		this.gradeArray.push(current_that.value);

		this.studentForm.studentNoArray = this.studentNoArray;
		this.studentForm.gradeArray = this.gradeArray;
	},
	changeCheckDate(){
		// 把获取的考勤时间使用 - 分割
		var dateArr = this.studentForm.checkDate.split("-");

		var year = parseInt(dateArr[0]); // 获取 年

		var month ; // 定义 月
		if(dateArr[1].indexOf("0") == 0){
			month = parseInt(dateArr[1].substring(1));
		}else{
			month = parseInt(dateArr[1]);
		}
		// 获取 日
		var day = parseInt(dateArr[2]);
		var _checkDate = new Date(year,month -1,day); // 把考勤时间转换为日期格式

		if(_checkDate>new Date()){
			alert("选择的卫生考核时间不能大于当前时间");
			this.studentForm.checkDate = new Date();
			this.studentForm.checkDate= this.format_date();
		}
		//alert("改变日期："+this.studentForm.checkDate)

		this.studentHygieneQueryParams.checkDate =this.studentForm.checkDate;
		this.studentHygieneQueryParams.bdormitoryId = this.studentForm.bdormitoryId;

		getStuByCheckDateAndBdormitoryId(this.studentHygieneQueryParams).then(response=> {
			this.studentHygieneList = response.data ;
			this.initStudentNoArrayAndGradeArray();
		})

	},
	/** 提交按钮 */
	submitStudentForm: function() {
	  this.$refs["studentForm"].validate(valid => {
	    if (valid) {
			addStudentHygiene(this.studentForm).then(response=>{
				if (response.code === 200) {
				  alert("卫生考核成功")
				  this.studentHygieneOpen = false;
				  this.$router.go(0);
				} else {
				  this.msgError(response.message);
				}
			})
	    }
	  });
	}
	,
	dormHygiene(row){

		this.dormOpen = true;
		this.reset();

		this.dormTitle = "宿舍卫生考核";
		//新增时隐藏被修改图片
		this.dialogVisible=false;
		this.activeUrl = process.env.VUE_APP_BASE_API +'/smartdor/manualHygiene/createHygiene';

		this.form.buildingNo = row.building_no;
		this.buildingNo = row.building_no;

	    this.form.storey = row.storey;
		this.storey = row.storey;

	    this.form.bdormitoryId = row.id;
		this.bdormitoryId = row.id;

	    this.form.dormitoryNo = row.name;
		this.dormitoryNo = row.name;

		this.queryParams.dormitoryId = row.id;
		let month = this.form.checkDate.getMonth()+1;
		if(month<10){
			month = "0"+month;
		}
		let date = this.form.checkDate.getDate();
		if(date <10){
			date = "0"+date;
		}
		let check_date= this.form.checkDate.getFullYear()+"-"+month+"-"+date;
		this.queryParams.checkDate = check_date ;
		this.callGetHygieneByDormitoryIdAdndCheckDate(this.queryParams)
	},

	changeHygieneDate(){
		this.isChange = true; // 如果是更改了日期则标记为 true
		// 把获取的考勤时间使用 - 分割
		var dateArr = this.form.checkDate.split("-");
		var year = parseInt(dateArr[0]); // 获取 年
		var month ; // 定义 月
		if(dateArr[1].indexOf("0") == 0){
			month = parseInt(dateArr[1].substring(1));
		}else{
			month = parseInt(dateArr[1]);
		}
		// 获取 日
		var day = parseInt(dateArr[2]);
		var _checkDate = new Date(year,month -1,day); // 把考勤时间转换为日期格式
		if(_checkDate>new Date()){
			alert("卫生考核时间不能大于当前时间");
			this.form.checkDate = new Date();
			let month = this.form.checkDate.getMonth()+1;
			if(month<10){
				month = "0"+month;
			}
			let date = this.form.checkDate.getDate();
			if(date <10){
				date = "0"+date;
			}
			let check_date= this.form.checkDate.getFullYear()+"-"+month+"-"+date;
			this.queryParams.checkDate = check_date;
		}else{
			this.queryParams.checkDate = this.form.checkDate ;

		}

		this.queryParams.dormitoryId = this.form.bdormitoryId;

		let _checkDate1 = this.form.checkDate ;
		this.reset();
		this.form.checkDate = _checkDate1;

		this.form.buildingNo = this.buildingNo;
		this.form.storey = this.storey;
		this.form.bdormitoryId = this.bdormitoryId;
		this.form.dormitoryNo = this.dormitoryNo;
		this.callGetHygieneByDormitoryIdAdndCheckDate(this.queryParams)
	}
	,
	callGetHygieneByDormitoryIdAdndCheckDate(query){
		getHygieneByDormitoryIdAdndCheckDate(query ).then(response=> {
			if(response.data!=null){
				//alert("表中存在数据")
				this.form.id = response.data.id;
				this.form.checkDate = response.data.checkDate;
				this.form.buildingNo = response.data.buildingNo;
				this.form.storey = response.data.storey;
				this.form.bdormitoryId = response.data.bdormitoryId;
				this.form.dormitoryNo = response.data.dormitoryNo;
				this.form.grade = response.data.grade;
				this.form.remark = response.data.remark;
				this.activeUrl = process.env.VUE_APP_BASE_API +'/smartdor/manualHygiene/updateAndUpload';

				if(response.data.photo !=null){
					//显示被修改的图片信息
					this.dialogVisible = true;
					this.dialogImageUrl = process.env.VUE_APP_BASE_API +'/smartdor/manualHygiene/getPhoto.do?id=' + this.form.id + '&width=200&height=200';
				}else{
					//隐藏图片信息
					this.dialogVisible = false;
				}
			}else{
				//alert("表中不存在数据。。。。。。。")
				this.activeUrl = process.env.VUE_APP_BASE_API +'/smartdor/manualHygiene/createHygiene';
			}
		})
	},

    // 取消按钮
    cancel() {
      this.dormOpen = false;
      this.reset();
    },

    // 表单重置
    reset() {
		this.form = {
			id: undefined,
			checkDate:new Date(),
			//第几栋楼
			buildingNo:undefined,
			//楼层
			storey:undefined,
			//宿舍ID
			bdormitoryId:undefined,
			//宿舍号
			dormitoryNo:undefined,
			remark:undefined,
			grade:undefined
		},
		this.dialogVisible=false
		//this.isChange=false;
    },

    /** 提交按钮 */
    submitForm: function() {
	   this.$refs["form"].validate(valid => {
	    if (valid) {
	        if (this.form.id !== undefined) {
	            if (!this.isHaveFile) {
					updateHygiene(this.form.id, this.form).then(response => {
						if (response.code === 200) {
							this.msgSuccess("修改成功");
							this.dormOpen = false;
							//this.getList();
						} else {
							this.msgError(response.message);
						}
					});
				} else {

					/*文件上传，附带表单数据*/
					this.form.photo=''
					this.$refs.upload.submit();
				}
	        } else {
				if (this.isHaveFile) {
					if (this.form.id == undefined) {
						this.form.id = '';
					}
					//格式化考核时间
					let check_date= this.form.checkDate.getFullYear()+"-"+(this.form.checkDate.getMonth()+1)+"-"+this.form.checkDate.getDate() ;
					this.form.checkDate = check_date;
					/*文件上传，附带表单数据*/
					this.$refs.upload.submit();
				}else{
					if(!this.isChange){
						//格式化考核时间

					   let month = this.form.checkDate.getMonth()+1;
					   if(month<10){
					   	month = "0"+month;
					   }

					   let date = this.form.checkDate.getDate();
					   if(date <10){
					   	date = "0"+date;
					   }
					   let check_date= this.form.checkDate.getFullYear()+"-"+month+"-"+date;
					   this.form.checkDate = check_date;
					}
					addHygiene(this.form).then(response => {
						if (response.code === 200) {
							this.msgSuccess("新增成功");
							this.dormOpen = false;
							//this.getList();
						} else {
							this.msgError(response.message);
						}
					});
					this.isChange=false;
				}
	        }
	    }
	  });
	   /*

      this.$refs["form"].validate(valid => {
        if (valid) {
			addManualAttence(this.form).then(response=>{
				if (response.code === 200) {
				  alert("考勤成功")
				  this.open = false;
				  this.$router.go(0);

				} else {
				  this.msgError(response.message);
				}
			})
        }
      });
	  */


    },

  }
};
</script>
